package labilabyrinth.activity;

import labilabyrinth.enums.GameState;
import labilabyrinth.game.GameSurface;
import labilabyrinth.game.R;
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.WindowManager;
import android.widget.Toast;

public class GameActivity extends Activity {

	private GameSurface gameSurface;
	private String levelName;
	private Bundle extras;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
		gameSurface = new GameSurface(this);
		extras = getIntent().getExtras();
		levelName = extras.getString("level");
		loadGame();
	}
	
	public void updateTitle() {
		this.setTitle("Level: " + levelName + " | Time: 00:00");
	}

	public boolean onCreateOptionsMenu(Menu menu) {
		menu.add(0, 0, 0, R.string.restart_lvl);
		return true;
	}

	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case 0:
			this.loadGame();
			gameSurface.pauseGame();
			break;
		}
		return true;
	}

	public void loadGame() {
		if (gameSurface != null) {
			gameSurface.state = GameState.RUNNING;
			if (gameSurface.loadLevel(levelName)) {
				Toast t = Toast.makeText(this.getApplicationContext(),
						R.string.lvl_load_success, Toast.LENGTH_SHORT);
				t.show();
				setContentView(gameSurface);
			} else {
				Toast t = Toast.makeText(this.getApplicationContext(),
						R.string.lvl_not_loaded, Toast.LENGTH_SHORT);
				t.show();
			}
		}
	}

	@Override
	public boolean onTouchEvent(MotionEvent event) {
		int e = event.getAction();
		if (e == MotionEvent.ACTION_DOWN) {
			if (gameSurface != null)
				if (gameSurface.state.equals(GameState.RUNNING)){
					gameSurface.pauseGame();
				}
				else if (gameSurface.state.equals(GameState.PAUSED)){
					gameSurface.resumeGame();
				}
					
		}
		return super.onTouchEvent(event);
	}

	@Override
	protected void onStart() {
		super.onStart();
	}

	@Override
	protected void onResume() {
		if (gameSurface != null)
			gameSurface.pauseGame();
		super.onResume();
	}

	@Override
	protected void onPause() {
		if (gameSurface != null)
			gameSurface.pauseGame();
		super.onPause();
	}

	@Override
	protected void onStop() {
		super.onStop();
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
	}
}
